import 'package:get/get.dart';
import 'package:gluz/app_session.dart';

import '../data/area_entity.dart';

class CommonServerController extends GetxController {
  List<AreaEntity> areaList = [];

  AreaEntity? selectedCountry;
  AreaEntity? selectedProvince;
  AreaEntity? selectedCity;

  bool get isSelectedCountry {
    return selectedCountry != null;
  }

  List<AreaEntity> historyAreaList = [];

  @override
  void onInit() {
    super.onInit();
  }
  void addHistory(AreaEntity entity) {
    historyAreaList.insert(0, entity);
    if (historyAreaList.length > 10) {
      historyAreaList.removeLast();
    }
  }

  Future<void> loadCountryList(int id) async {
    areaList =
        await app.http.request(
          path: '/api/area/list',
          params: {
            'pid': id
          },
          options: app.http.forceCacheOptions(),
          fromJson: (e) => List<Map<String, dynamic>>.from(
            e,
          ).map((e) => AreaEntity.fromJson(e)).toList(),
        ) ??
        [];
    areaList = areaList.where((e) { return e.country >= 0; }).toList();
    areaList.sort((a, b) {
      return a.country - b.country;
    });
    update();
  }
}
